package com.cooper.beautyseesee;

import java.util.ArrayList;
import java.util.List;

import com.cooper.beautyseesee.data.BeautyType;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class BeautyTypeFragment extends ListFragment {

	public static BeautyTypeFragment newInstance(ArrayList<BeautyType> types) {
		BeautyTypeFragment result = new BeautyTypeFragment();
		Bundle bundle = new Bundle();
		bundle.putParcelableArrayList("BEAUTY_TYPES", types);
		result.setArguments(bundle);
		return result;
	}

	private List<BeautyType> types;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.list, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		BeautyTypeAdapter adapter = new BeautyTypeAdapter(getActivity());

		types = getArguments().getParcelableArrayList("BEAUTY_TYPES");

		for (BeautyType type : types) {
			adapter.add(type);
		}

		setListAdapter(adapter);

	}

	@Override
	public void onListItemClick(ListView lv, View v, int position, long id) {

		if (getActivity() == null)
			return;

		if (getActivity() instanceof MainActivity) {
			MainActivity fca = (MainActivity) getActivity();
			fca.switchBeautyListFragment(types.get(position));
		}
	}

	public class BeautyTypeAdapter extends ArrayAdapter<BeautyType> {

		public BeautyTypeAdapter(Context context) {
			super(context, 0);
		}

		@SuppressWarnings("deprecation")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getContext()).inflate(
						R.layout.type_item, null);
			}
			ViewGroup item = (ViewGroup) convertView
					.findViewById(R.id.type_item_layout);

			BeautyType itemType = getItem(position);

			if (itemType.getBackgroundUri() == null
					|| "".equals(itemType.getBackgroundUri())) {
				item.setBackgroundResource(R.drawable.random);
			} else

				item.setBackgroundDrawable(BitmapDrawable
						.createFromPath(itemType.getBackgroundUri()));

			TextView title = (TextView) convertView
					.findViewById(R.id.type_name);
			title.setText(itemType.getName());

			return convertView;
		}
	}
}
